<template>
    <div>
        <vxe-button
            style="margin-bottom: 10px"
            icon="vxe-icon-add"
            type="primary"
            size="mini"
            status="primary"
            @click="editEvent('add')"
            >添加品牌</vxe-button
        >
        <vxe-table
            align="center"
            :loading="loading"
            :loading-config="{
                icon: 'vxe-icon-spinner roll',
                text: '加载中...',
            }"
            :seq-config="seqConfig"
            size="small"
            border
            height="500px"
            :data="tableData"
        >
            <!-- 序号 -->
            <vxe-column
                style="vertical-align: middle"
                type="seq"
                title="序号"
                width="100"
            >
            </vxe-column>
            <!-- 品牌名称 -->
            <vxe-column title="品牌名称" field="tmName"></vxe-column>
            <!-- 品牌logo -->
            <vxe-column title="品牌logo" field="logoUrl">
                <template #default="{ row }">
                    <el-image
                        style="height: 100px"
                        :src="row.logoUrl"
                        fit="fill"
                    />
                </template>
            </vxe-column>
            <!-- 品牌操作 -->
            <vxe-column title="品牌操作" width="200">
                <template v-slot="scope">
                    <el-button
                        type="warning"
                        icon="Edit"
                        @click="editEvent('edit', scope.row)"
                    ></el-button>
                    <el-popconfirm
                        title="确认删除吗?"
                        icon="DeleteFilled"
                        icon-color="rgb(228, 116, 112)"
                        @confirm="confirmToDeleteItem(scope.row.id)"
                    >
                        <template #reference>
                            <el-button type="danger" icon="delete"></el-button>
                        </template>
                    </el-popconfirm>
                </template>
            </vxe-column>
        </vxe-table>
        <el-pagination
            :small="true"
            height="200"
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[3, 6, 9]"
            :background="true"
            layout="prev ,pager,next,total, ->,sizes,   jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
        <vxe-modal
            v-model="showEdit"
            width="800"
            resize
            destroy-on-close
            :title="addOrEditFlag ? '修改' : '新增'"
        >
            <template #default>
                <el-form
                    ref="form"
                    :rules="rules"
                    :model="formData"
                    label-width="120px"
                >
                    <el-form-item label="品牌名称" prop="brandName">
                        <el-input
                            v-model="formData.brandName"
                            placeholder="请输入品牌名称"
                            style="width: 50%"
                        ></el-input>
                    </el-form-item>
                    <el-form-item label="品牌logo" prop="brandLogo">
                        <el-upload
                            class="avatar-uploader"
                            action="/api/admin/product/fileUpload"
                            :show-file-list="false"
                            :on-success="handleLogoSuccess"
                            :before-upload="beforeLogoUpload"
                        >
                            <img
                                v-if="formData.brandLogo"
                                :src="formData.brandLogo"
                                class="avatar"
                            />
                            <el-icon v-else class="avatar-uploader-icon"
                                ><Plus
                            /></el-icon>
                        </el-upload>
                    </el-form-item>
                    <el-form-item :span="24">
                        <el-button type="default" @click="hanleCancel"
                            >取消</el-button
                        >
                        <el-button type="primary" @click="handleAddBrand"
                            >提交</el-button
                        >
                    </el-form-item>
                </el-form>
            </template>
        </vxe-modal>
    </div>
</template>

<script>
import { defineComponent, ref, reactive, onMounted } from "vue"
import {
    getDataList,
    addBrand,
    updateBrand,
    deleteBrand,
} from "@/api/product/brand/index"
import { ElMessage } from "element-plus"

export default defineComponent({
    name: "brand",
    setup() {
        onMounted(() => {
            getData()
        })
        // 查询表格数据
        function getData() {
            // 开启loading
            loading.value = true
            getDataList(currentPage.value, pageSize.value)
                .then((res) => {
                    loading.value = false
                    tableData.value = res.data.records
                    total.value = res.data.total
                })
                .catch(() => {
                    loading.value = false
                })
        }
        let tableData = ref([])
        let formData = reactive({
            brandName: "",
            brandLogo: "",
            id: null,
        })

        let currentPage = ref(1)
        let pageSize = ref(3)
        let total = ref(1)
        let loading = ref(false)
        let showEdit = ref(false)
        let addOrEditFlag = ref(false)
        let form = ref()

        // 表单校验规则
        const rules = ref({
            brandName: [
                { required: true, message: "请输入名称" },
                { min: 3, max: 5, message: "长度在 3 到 5 个字符" },
            ],
            brandLogo: [{ required: true, message: "请选择图片" }],
        })

        // 修改当前页
        function handleCurrentChange(val) {
            getData()
        }

        // 修改每页条数
        function handleSizeChange() {
            currentPage.value = 1
            getData()
        }

        // 点击编辑或点击新增
        const editEvent = (status, row) => {
            /* 根据状态修改title */
            if (status === "edit") {
                addOrEditFlag.value = true
                // console.log("row", row)
                formData.brandLogo = row.logoUrl
                formData.brandName = row.tmName
                formData.id = row.id
            } else if (status === "add") {
                addOrEditFlag.value = false
                formData.brandLogo = ""
                formData.brandName = ""
            }
            showEdit.value = true
        }

        // 序号
        const seqConfig = reactive({
            seqMethod({ rowIndex }) {
                return (currentPage.value - 1) * pageSize.value + rowIndex + 1
            },
        })

        // 上传图片的校验
        function beforeLogoUpload(rawFile) {
            console.log("rawFile", rawFile)
            if (rawFile.type !== "image/jpeg" && rawFile.type !== "image/png") {
                ElMessage.error("图片的格式必须为JPG或png!")
                return false
            } else if (rawFile.size / 1024 / 1024 > 4) {
                ElMessage.error("图片的大小不能超过4Mb!")
                return false
            }
            return true
        }

        // 上传成功后的处理函数
        function handleLogoSuccess(res) {
            if (res.code === 200 && res.ok) {
                formData.brandLogo = res.data
                // 移除对品牌logo的校验
                form.value.clearValidate(["brandLogo"])
            } else {
                ElMessage.error(res.message)
            }
        }

        // 添加品牌或者修改品牌
        function handleAddBrand() {
            form.value.validate(async (valid) => {
                if (valid) {
                    let res
                    if (addOrEditFlag.value) {
                        console.log("to 修改")
                        // 修改
                        res = await updateBrand({
                            id: formData.id,
                            logoUrl: formData.brandLogo,
                            tmName: formData.brandName,
                        })
                    } else {
                        console.log("to 添加")
                        // 添加
                        res = await addBrand({
                            logoUrl: formData.brandLogo,
                            tmName: formData.brandName,
                        })
                    }
                    if (res.code === 200 && res.ok) {
                        addOrEditFlag.value ? "" : (currentPage.value = 1)
                        ElMessage({
                            type: "success",
                            message: addOrEditFlag.value
                                ? "修改成功"
                                : "添加成功",
                        })
                    } else {
                        ElMessage({
                            type: "error",
                            message: addOrEditFlag.value
                                ? "修改失败"
                                : "添加失败",
                        })
                    }
                    showEdit.value = false
                    getData() // 查询
                }
            })
        }

        // 添加取消
        const hanleCancel = () => {
            showEdit.value = false
        }

        // 确认删除
        function confirmToDeleteItem(id) {
            // console.log("id", id)
            deleteBrand(id)
                .then((res) => {
                    if (res.code === 200) {
                        ElMessage({
                            type: "success",
                            message: res.message,
                        })
                        // 删除成功，判断当前页需不需要减1
                        tableData.value.length === 1 && currentPage.value !== 1
                            ? currentPage.value--
                            : ""
                    } else {
                        ElMessage({
                            type: "error",
                            message: res.message,
                        })
                    }
                    getData() // 再次查询
                })
                .catch(() => {})
        }

        return {
            currentPage,
            pageSize,
            total,
            tableData,
            handleCurrentChange,
            handleSizeChange,
            loading,
            seqConfig,
            editEvent,
            showEdit,
            addOrEditFlag,
            formData,
            beforeLogoUpload,
            handleLogoSuccess,
            handleAddBrand,
            hanleCancel,
            rules,
            form,
            confirmToDeleteItem,
        }
    },
})
</script>

<style scoped lang="scss">
.el-pagination {
    margin-top: 10px;
}
@keyframes l27 {
    100% {
        transform: rotate(1turn);
    }
}

.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>
